const router = require('koa-router')()
const { register, login } = require('../controller/userWeb')
const loginCheck = require('../middleware/loginCheck')

router.prefix('/users')


// 获取用户信息;要先校验用户已登录
router.get('/getUserInfo', loginCheck, async (ctx) => {
  ctx.body = { errno: 0, data: ctx.session.userInfo }
})

// 登录
router.post('/login', async (ctx) => {
  const { username, password } = ctx.request.body // 获取登录信息
  console.log(`/login username = ${username}; password = ${password}`)
  const responseModel = await login(username, password) // 验证登录
  console.log('be login ==>responseModel =\n', responseModel)
  if (responseModel.ok) ctx.session.userInfo = responseModel.data // 登录成功;设置session
  ctx.body = responseModel
})

// 注册
router.post('/register', async (ctx) => {
  const userInfo = ctx.request.body // 获取请求体
  const responseModel = await register(userInfo) // 提交注册
  console.log('be register==>responseModel\n',responseModel)
  if (!responseModel.ok) ctx.status = 500  // 默认值是 200
  ctx.body = responseModel
})


module.exports = router
